<template>
  <div class="page">
    <div class="container">
      <pub-search
        v-model:searchColumns="state.searchColumns"
        v-model:searchForm="state.searchForm"
        mask-append-to="table-container"
        @search="getPageData"
      >
        <template #leftBtn>
          <el-button
            :icon="Plus"
            class="btn-table-add"
            type="primary"
            @click="add('')"
          >
            新增
          </el-button>
        </template>
      </pub-search>
      <div class="table-container">
        <pub-table
          ref="pubTable"
          :column="state.columns"
          :data="state.tableData"
          :loading="tableLoading"
        >
          <template v-slot:switch="scope">
            <el-switch
              :model-value="scope.row.status == 1"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="changeStatus(scope.row)"
            />
          </template>
          <template v-slot:option="scope">
            <el-button
              class="btn-row-edit"
              plain
              type="success"
              @click="edit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              plain
              class="btn-row-del"
              type="danger"
              @click="del(scope.row)"
            >
              删除
            </el-button>
            <el-dropdown style="margin-left: 10px" size="medium">
              <el-button style="color:#087CD6">
                更多
                <el-icon class="el-icon--right">
                  <arrow-down />
                </el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click.native="roleSelect(scope.row)">
                    角色分配
                  </el-dropdown-item>
                  <el-dropdown-item @click.native="resetPWDMethods(scope.row)">
                    重置密码
                  </el-dropdown-item>
                  <el-dropdown-item
                    @click.native="cancelDisableMethods(scope.row)"
                  >
                    解除锁定
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </pub-table>
      </div>
      <pub-pagination
        :total="total"
        v-model:page="state.searchForm.pageNum"
        v-model:limit="state.searchForm.pageSize"
        @pagination="getPageData"
      />
      <!-- 添加/编辑弹窗 -->
      <pub-dialog
        v-if="dialogFormVisible_add"
        :title="popTitle"
        v-model:visible="dialogFormVisible_add"
        width="1000px"
        @close="close"
      >
        <dialogEdit
          ref="dialogEditRef"
          :edit-id="editId"
          :is-edit="isEdit"
          @close="close"
          @submitForm="submitForm"
        />
      </pub-dialog>
      <!-- 角色分配弹窗 -->
      <pub-dialog
        v-if="dialogFormVisible_role"
        :title="popTitle"
        v-model:visible="dialogFormVisible_role"
        width="1000px"
        @close="close"
      >
        <dialogRole :role-ids="roleIds" @saveRole="saveRole" />
      </pub-dialog>
    </div>
  </div>
</template>

<script setup>
import {
  changeResourceStatus,
  resetPWD,
  cancelDisable,
  saveRoleInfos,
  getAccountList,
  accountAddSubmit,
  delAccount
} from '@/api/system'
import { ref, reactive, toRefs, onMounted } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import dialogEdit from './add.vue'
import dialogRole from './role.vue'
import { useUserStore } from '@/pinia/modules/user'
import {
  Delete,
  Edit,
  Search,
  Share,
  Upload,
  Plus
} from '@element-plus/icons-vue'
import { Sm4Dncrypt } from '@/utils/encryption.js'
const userStore = useUserStore()
const userAreaArr = userStore.userAreaArr
const orgInfo = userStore.orgInfo

const isEdit = ref(false)
const roleIds = ref('')
const editId = ref('')
const dialogFormVisible_role = ref(false)
const dialogFormVisible_add = ref(false)
const popTitle = ref('')
const tableLoading = ref(false)
const total = ref(0)
const state = reactive({
  searchColumns: [
    {
      label: '机构名称',
      el: 'Input',
      bind: 'orgName',
      defaultValue: '',
      labelWidth: 80
    },
    {
      label: '所属社区',
      el: 'AreaSelect',
      bind: 'areaCode',
      defaultValue: '',
      disabledLevel: useUserStore().orgInfo.level - 1,
      defaultArea: useUserStore().userAreaArr,
      labelWidth: 80
    },
    {
      label: '登录名',
      el: 'Input',
      bind: 'userName',
      defaultValue: '',
      labelWidth: 140
    },
    {
      label: '启用状态',
      el: 'DictSelect',
      bind: 'status',
      defaultValue: '',
      code: 'QYZT',
      labelWidth: 80
    }
  ],
  tableData: [],
  searchForm: {
    pageSize: 15,
    pageNum: 1
  },
  columns: [
    { label: '名称', prop: 'realName',width:180 },
    { label: '登录名', prop: 'userName',width:120 },
    {
      label: '状态',
      prop: 'status',
      type: 'formatDict',
      formatCode: 'QYZT'
    },
    { label: '创建时间', prop: 'createDate',width:180 },
    {
      label: '所属角色',
      prop: 'roleNames',
      showToolTip: true
    },
    { label: '是否禁用', type: 'switch', prop: 'status' },
    { label: '操作', type: 'option', width: '220',fixed:'right' }
  ]
})
const dialogEditRef = ref(null)

const fetchList = () => {
  state.searchForm.pageNum = 1
  getPageData()
}

const changeStatus = async row => {
  let newStatus
  if (row.status == 1) {
    newStatus = 0
    row.status = 0
  } else if (row.status == 0) {
    newStatus = 1
    row.status = 1
  }
  const params = {
    status: newStatus
  }
  let result = await changeResourceStatus(row.id, params)
  if (result.succeed) {
    ElMessage.success(result.msg)
  } else ElMessage.error(result.msg)
}
const cancelDisableMethods = async row => {
  ElMessageBox.confirm('是否解锁此账号?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    confirmButtonClass: 'btn-row-edit',
    cancelButtonClass: 'btn-row-close',
    type: 'warning'
  })
    .then(async () => {
      let result = await cancelDisable(row.id)
      if (result.succeed) {
        ElMessage.success('解锁成功')
        fetchList()
      } else ElMessage.error('解锁失败！')
    })
    .catch(err => {})
}
const saveRole = async formData => {
  let result = await saveRoleInfos(formData)
  if (result.succeed) {
    ElMessage.success(result.msg)
    close()
    fetchList()
  } else ElMessage.error(result.msg)
}
const resetPWDMethods = async row => {
  ElMessageBox.confirm('此操作将该用户密码重置, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    confirmButtonClass: 'btn-row-edit',
    cancelButtonClass: 'btn-row-close',
    type: 'warning'
  })
    .then(async () => {
      let result = await resetPWD(row.id)
      if (result.succeed) {
        // ElMessage.success('重置成功')
        ElMessageBox.alert(`重置密码成功！重置后的密码是：${Sm4Dncrypt(result.data)}`, {
                confirmButtonText: '确定',
                callback: action => {
                  console.log(action)
                }
              })
        fetchList()
      } else ElMessage.error('重置失败！')
    })
    .catch(err => {})
}
const roleSelect = row => {
  roleIds.value = row.id
  dialogFormVisible_role.value = true
  popTitle.value = '角色分配'
}
const del = async row => {
  ElMessageBox.confirm('确认删除选择的记录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    confirmButtonClass: 'btn-row-edit',
    cancelButtonClass: 'btn-row-close',
    type: 'warning'
  })
    .then(async () => {
      let result = await delAccount(row.id)
      if (result.succeed) {
        ElMessage.success('删除成功')
        getPageData()
      } else ElMessage.error('删除失败！')
    })
    .catch(err => {})
}
const close = () => {
  editId.value = ''
  dialogFormVisible_add.value = false
  dialogFormVisible_role.value = false
}
const submitForm = async formData => {
  const requestType = isEdit.value ? 'put' : 'post'
  let res = await accountAddSubmit(formData, requestType)
  if (res.succeed) {
    // ElMessage.success(isEdit.value ? '修改成功' : '添加成功')
    if(!isEdit.value){
      ElMessageBox.alert(`您的初始密码为：${Sm4Dncrypt(res.data)}`, {
        confirmButtonText: '确定',
        callback: action => {
          console.log(action)
        }
      })
    }else{
      ElMessage.success(res.msg);
    }
    isEdit.value = false
    close()
    console.log(dialogEditRef)
    dialogEditRef.value.load()
    fetchList()
  } else {
    ElMessage.error(res.msg)
    dialogEditRef.value.load()
  }
}
const add = row => {
  popTitle.value = '新增用户'
  dialogFormVisible_add.value = true
  isEdit.value = false
}
const edit = row => {
  popTitle.value = '编辑用户'
  editId.value = row.id
  dialogFormVisible_add.value = true
  isEdit.value = true
}

const getPageData = async () => {
  tableLoading.value = true
  let res = await getAccountList(state.searchForm)
  if (res.succeed) {
    state.tableData = res.data
    total.value = res.total
  }
  tableLoading.value = false
}

onMounted(() => {
  getPageData()
})
</script>
<style scoped>
/* 当列表有两行筛选条件使用 */
.table-container {
  height: calc(100% - 130px);
  flex: 1;
}
.table-web {
  height: 100% !important;
}
/* 当列表有两行筛选条件使用 */
</style>
